<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon>
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader v-model="selectedKeys" :options="cateList" expand-trigger="hover" :props=" cateProps" @change="cascaderChange"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="showAddDialog" :disabled="isBtnDisable">添加参数</el-button>
          <el-table border stripe :data="manyTableData" style="width: 100%">
            <el-table-column type="expand" width="80">
              <template slot-scope="scope">
                <el-tag :key="i" v-for=" (item,i)  in scope.row.attr_vals" closable @close="handleTagClose(i,scope.row)">
                  {{item }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="showEditDialog(scope.row.attr_id)" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" @click="removeById(scope.row.attr_id)" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">

          <el-button type="primary" @click="showAddDialog" :disabled="isBtnDisable">添加属性</el-button>
          <el-table border stripe :data="onlyTableData" style="width: 100%">
            <el-table-column type="expand" width="80">
              <template slot-scope="scope">
                <el-tag :key="i" v-for=" (item,i)  in scope.row.attr_vals" closable @close="handleTagClose(i,scope.row)">
                  {{item }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="showEditDialog(scope.row.attr_id)" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" @click="removeById(scope.row.attr_id)" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加表单数据 -->
      <el-dialog :title=" '添加'+titleText" @close='addDialogClose' :visible.sync="addDlalogVisible" width="50%">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDlalogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSubmitBtn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改表单数据 -->
      <el-dialog :title=" '添加'+titleText" :visible.sync="editDlalogVisible" width="50%">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDlalogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSubmitBtn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      selectedKeys: [],
      activeName: 'many',
      onlyTableData: [],
      manyTableData: [],
      addDlalogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '此选项不能为空！', trigger: 'blur' }]
      },
      editDlalogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [{ required: true, message: '此选项不能为空！', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
    },
    cascaderChange() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
      } else {
        this.getTableData()
      }
    },
    handleTabClick() {
      this.getTableData()
    },
    async getTableData() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取表格数据失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        item.inputValue = ''
        item.inputVisible = false
      })
      if (this.activeName === 'many') {
        return (this.manyTableData = res.data)
      } else {
        return (this.onlyTableData = res.data)
      }
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        row.attr_vals.push(row.inputValue.trim())
        this.saveAttrVal(row)
        row.inputValue = ''
        row.inputVisible = false
      }
    },
    handleTagClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVal(row)
    },
    async saveAttrVal(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/` + row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数项成功！')
      row.children = res.data
    },
    showAddDialog() {
      this.addDlalogVisible = true
    },
    addSubmitBtn() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加数据失败！')
        }
        this.$message.success('添加数据成功！')
        this.getTableData()
        this.addDlalogVisible = false
      })
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/` + id, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.editForm = res.data
      this.editDlalogVisible = true
    },
    editSubmitBtn() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/` + this.editForm.attr_id, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新数据失败！')
        }
        this.$message.success('更新数据成功！')
        this.getTableData()
        this.editDlalogVisible = false
      })
    },
    async removeById(id) {
      const ConfirmResult = await this.$confirm('此操作将永久删除该参数/属性, 是否继续 ？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (ConfirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/` + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败！')
      }
      this.$message.success('删除数据成功！')
      this.getTableData()
    }
  },
  computed: {
    cateId() {
      if (this.selectedKeys.length !== 3) {
        return null
      } else {
        return this.selectedKeys[this.selectedKeys.length - 1]
      }
    },
    isBtnDisable() {
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-col {
  margin: 10px 0;
  span {
    margin-right: 10px;
  }
}
.el-cascader {
  width: 300px;
}

.input-new-tag {
  width: 200px;
}
.el-table .el-tag {
  margin: 5px 10px 5px 0;
}
</style>
